<template>
  <a-select
    :placeholder="placeholder"
    :options="selectOptions"
    :loading="loading"
    :getPopupContainer="node => node.parentNode"
    :show-search="showSearch"
    :filter-option="filterOption"
    option-filter-prop="label"
    v-bind="$attrs"
    v-on="$listeners"
  >
  </a-select>
</template>

<script>
export default {
  name: 'CDict',
  props: {
    showSearch: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    dictType: {
      type: String,
      required: true
    },
    resource: {
      type: Array,
      required: false
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      options: [],
      loading: false,
      action: '/baseData/listByType'
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    fetchList() {
      this.loading = true
      this.$http
        .get(this.action, {
          params: {
            dictTypes: this.dictType
          }
        })
        .then(res => {
          if (res.success && res.result) {
            this.options = res.result.map(item => {
              let { typeCode = '', classCode = '', typeName, className } = item
              if (typeCode === null) typeCode = ''
              if (classCode === null) classCode = ''
              return {
                value: `${typeCode}${classCode}`,
                label: className || typeName
              }
            })
            this.$emit('loaded', this.options)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  },
  computed: {
    selectOptions() {
      return this.resource || this.options || []
    }
  }
}
</script>

<style></style>
